package com.orilx.lowtea.article

import com.orilx.lowtea.web.pageParams
import com.orilx.lowtea.web.userIdOrNull
import com.orilx.lowtea.web.userId
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.web.servlet.function.body
import org.springframework.web.servlet.function.paramOrNull
import org.springframework.web.servlet.function.router

@Configuration(proxyBeanMethods = false)
class ArticleRouterConfiguration {
    @Bean
    fun articleRouter(service: ArticleService) = router {

        /**
         * 根据参数列出所有帖子或者指定用户的帖子
         */
        GET("/articles") {
            val userId = it.userIdOrNull()
//            val author = it.paramOrNull("author")
            val pageParams = it.pageParams()
            val articles = service.listArticle(userId, pageParams)
            val count = service.countArticle(userId)
            ok().body(ArticlesResponse(articles, count))
        }

        /**
         * 获取帖子详情
         */
        GET("/articles/{slug}") {
            val userId = it.userIdOrNull()
            val slug = it.pathVariable("slug")
            val model = service.getArticle(userId, slug)
            ok().body(ArticleResponse(model))
        }

        /**
         * 发帖
         */
        POST("/articles") {
            val userId = it.userId()
            val payload = it.body<ArticleCreateRequest>().article
            val model = service.createArticle(userId, payload)
            ok().body(ArticleResponse(model))
        }

        /**
         * 根据 slug 删除帖子
         */
        DELETE("/articles/{slug}") {
            val userId = it.userId()
            val slug = it.pathVariable("slug")
            service.deleteArticle(userId, slug)
            ok().build()
        }


    }
}